package cn.rengy.auth.token;

import cn.rengy.auth.AuthenToken;
import cn.rengy.auth.exception.AuthException;
import org.apache.commons.lang3.StringUtils;

public abstract class AbstractAuthenTokenCreator implements AuthenTokenCreator {
    private final String tokenType;


    protected AbstractAuthenTokenCreator(String tokenType){
        this.tokenType =tokenType;
    }

    @Override
    public String getTokenType(){
        return tokenType;
    }
    @Override
    public boolean supports(Object request) {
        String authHeader= getAuthorization(request);
        if(authHeader==null){
            return false;
        }
        return authHeader.startsWith(tokenType);
    }

    protected abstract String getAuthorization(Object request);

    @Override
    public AuthenToken getAuthenticationToken(Object request) {
        if(!supports(request)){
            throw new AuthException(401,"不支持此Request");
        }
        String authHeader= getAuthorization( request);
        if(StringUtils.isEmpty(authHeader)){
            throw new AuthException(401,"获取Header信息为空");
        }
        String authToken = authHeader.substring(tokenType.length());
        if(StringUtils.isEmpty(authToken)) {
            throw new AuthException(401,"获取Token信息为空");
        }
        authToken=authToken.trim();
        return createToken( authToken, request);
    }

    protected abstract AuthenToken createToken(String token, Object request);
}
